<template>
    <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
            <div class="fire-station-info-wrap">
                <el-form label-width="150px" :model="fireStationForm" :rules="fireStationFormRules" ref="fireStationForm" @submit.native.prevent>
                    <el-form-item label="业主单位：" prop='organizationId'>
                        <el-select filterable v-model="fireStationForm.organizationId">
                            <el-option
                                v-for="item in orgList"
                                :key="item.organizationId"
                                :label="item.shortName"
                                :value="item.organizationId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="名称：" prop="name">
                        <el-input v-model="fireStationForm.name" auto-complete="off" placeholder="请输入名称"></el-input>
                    </el-form-item>
                    <el-form-item label="位置：" prop="location">
                        <el-input v-model="fireStationForm.location" auto-complete="off" placeholder="请输入位置"></el-input>
                    </el-form-item>
                    <el-form-item label="联系电话：" prop="tel">
                        <el-input v-model="fireStationForm.tel" auto-complete="off" placeholder="请输入联系电话"></el-input>
                    </el-form-item>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="经度：" prop="lon">
                                <el-input v-model="fireStationForm.lon" auto-complete="off" placeholder="请输入经度"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="纬度：" prop="lat">
                                <el-input v-model="fireStationForm.lat" auto-complete="lat" placeholder="请输入纬度"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="选取经纬度：">
                        <div id="FireStationBaiduMap" style="width:100%;height:300px"></div>
                        <input id="unitName_mapInput" class="form-control" v-model="valtemp" placeholder="请输入地点"/>
                    </el-form-item>
                    <el-form-item label="消防人员数：" prop="personCount">
                        <el-input type="number" v-model="fireStationForm.personCount" auto-complete="off" placeholder="请输入消防人员数"></el-input>
                    </el-form-item>
                    <el-form-item label="消防车数：" prop="carCount">
                        <el-input type="number" v-model="fireStationForm.carCount" auto-complete="off" placeholder="请输入消防车数"></el-input>
                    </el-form-item>
                    <el-form-item label="图片：" prop='pictures'>
                        <el-upload
                            :action="QINIUUPLOADURL"
                            :multiple="false"
                            ref="upload"
                            list-type="picture-card"
                            :data="qiniuData"
                            :on-success="handleAvatarSuccess"
                            :on-remove="handleRemovePic"
                            :on-error="handleError"
                            :before-upload="beforeAvatarUpload"
                            :on-preview="$imgPreview"
                            :file-list="qiniuData.fileList"
                            :limit="1"
                            :on-exceed="handleExceed"
                            accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label-width="0" class="verifyidentity-button">
                        <el-button @click.stop="closeFun" round>取消</el-button>
                        <el-button type="primary" @click="saveInfo('fireStationForm')" round>保存</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-col>
    </el-row>
</template>
<script>
import BMap from 'BMap'
import util from '@/utils/util'
import { qnToken} from '@/api/api'
import { getOrgList } from '@/api/org'
import { updateFireHouses } from '@/api/sysConfig'
import { setTimeout } from 'timers';

var map
export default {
  name:'ImportAsset',
  props: {
    oldInfo: {},
    closeFun: {
      type: Function,
      required: true,

    }
  },
  data() {
    return {
        valtemp: '',
        qiniuData:{//上传图片携带的参数
            token : "",
            key : "",
            fileList:[],
        },
        orgList: [],
        fireStationForm: {
            organizationId: '',
            name: '',
            location: '',
            lat: '',
            lon: '',
            personCount: '',
            carCount: '',
            tel: '',
            id: ''
        },
        fireStationFormRules: {
            organizationId: [
                { required: true, message: '请选择业主单位', trigger: 'change' }
            ],
            name: [
                { required: true, message: '请输入名称', trigger: 'blur' }
            ],
            personCount:[
                {pattern:/^[+]{0,1}(\d+)$/ , message:'请输入正确的数值'}
            ],
            carCount:[
                {pattern:/^[+]{0,1}(\d+)$/ , message:'请输入正确的数值'}
            ]
        }
    }
  },
  created() {
    let that = this
    that.getToken()
    // 获取业主单位信息
    getOrgList({
        queryType: 0
    }).then(res => {
        if(res.status = 200) {
          if (!that.oldInfo.id) {
            that.fireStationForm.organizationId = res.data[0].organizationId
          }
            that.orgList = res.data
        }
    })
    that.$nextTick(() => {
        // 是否有历史值
        if(that.oldInfo.id) {
            that.fireStationForm.organizationId = that.oldInfo.organizationId
            that.fireStationForm.name = that.oldInfo.name
            that.fireStationForm.location = that.oldInfo.location
            that.fireStationForm.lat = that.oldInfo.lat
            that.fireStationForm.lon = that.oldInfo.lon
            that.fireStationForm.personCount = that.oldInfo.personCount
            that.fireStationForm.carCount = that.oldInfo.carCount
            that.fireStationForm.tel = that.oldInfo.tel
            that.fireStationForm.id = that.oldInfo.id
            // 设置上传图片初始值
            that.oldInfo.url ? $.each(that.oldInfo.url.split(','), (index,url) => {
                that.qiniuData.fileList.push({
                    name: that.oldInfo.name + index,
                    url:url
                })
            }) : ''
        }
        // 初始化地图
        that.initMap()
    })
  },
  methods: {
    // 地图初始化
    initMap() {
        let that = this
        var geoc = new BMap.Geocoder()
        //选取经纬度
        map = new BMap.Map("FireStationBaiduMap")
        map.enableScrollWheelZoom() // 允许缩放
        map.clearOverlays() // 先清除地图上的点
        map.enableKeyboard() // 启用键盘上下左右键移动地图
        map.setDefaultCursor("crosshair") // 设置鼠标样式

        //经纬度画线
        if(that.oldInfo.lon && that.oldInfo.lat){
            var new_point1 = new BMap.Point(that.oldInfo.lon, that.oldInfo.lat);
            var marker1 = new BMap.Marker(new_point1);  // 创建标注
            map.addOverlay(marker1);              // 将标注添加到地图中
            map.centerAndZoom(new_point1,16);
            //map.panTo(new_point1);
        }else{
            var position = new BMap.Point(116.331398,39.897445);
            map.centerAndZoom(position, 16);
        }

        map.addEventListener("click", function(e){
            // 通过点击百度地图，可以获取到对应的point, 由point的lng、lat属性就可以获取对应的经度纬度
            var pt = e.point;
            geoc.getLocation(pt, function(rs){
                // addressComponents对象可以获取到详细的地址信息
                var addComp = rs.addressComponents;
                // 位置值
                that.fireStationForm.location=addComp.province+","+addComp.city+","+addComp.district+","+addComp.street+","+addComp.streetNumber
                // 打点
                map.clearOverlays() // 先清除地图上的点
                var marker = new BMap.Marker(pt);  // 创建标注
                map.addOverlay(marker);              // 将标注添加到地图中
                // 经纬度设置值
                that.fireStationForm.lon = pt.lng
                that.fireStationForm.lat = pt.lat
            })
        })
        setTimeout(() => {
            that.mapSearch()
        }, 1000)
    },
    // 搜索经纬度
    mapSearch() {
        var acSearch = new BMap.Autocomplete(
            {'input' : 'unitName_mapInput', 'location' : map}
        );
        acSearch.setInputValue(this.valtemp);
        acSearch.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件
            var _value = e.item.value;
            var myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
            var local = new BMap.LocalSearch( map, { //智能搜索
                onSearchComplete: function(results){
                    var position=results.getPoi(0);//得到标注点坐标
                    var lng = position.point.lng;
                    var lat = position.point.lat;
                    var gpsPoint = new BMap.Point(lng,lat);
                    map.centerAndZoom(gpsPoint,16);
                }
            });
            local.search(myValue);
        });
    },
    getToken(){  //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token= result.data
      })
    },
    beforeAvatarUpload(file) {//重命名和校验
      var fielLocal = file.name.split(".")
      var fielType = "." + fielLocal[fielLocal.length-1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_'+new Date().getTime()+fielType
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isJPG && !isPNG) {
        this.$message.error("图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt20M) {
        this.$message.error("图片大小不能超过 20MB!");
        return false;
      }
    },
    handleAvatarSuccess: function(res, file, fileList) {//上传成功
      this.qiniuData.fileList = fileList;
    },
    handleRemovePic: function(file, fileList) {//删除成功
      this.qiniuData.fileList = fileList;
    },
    handleError: function(res) {
      this.$message({
        message: "上传失败",
        duration: 2000,
        type: "warning"
      });
    },
    handleExceed(files, fileList) {//文件超出个数限制时的钩子
      this.$message.warning(`只能上传一张图片！`);
    },
    // 保存
    saveInfo(formName) {
        // 阻止事件冒泡
        event.stopPropagation()
        let that = this

        that.$refs[formName].validate((valid) => {
            if (valid) {
                let parames = that.fireStationForm
                parames.url = util.ilinkArrHandle.getqiniuPicUrlArr(that.qiniuData.fileList).toString()
                // 提交
                updateFireHouses(parames).then(res => {
                    if(res.status === 200) {
                        that.$message({
                            message: '保存成功！',
                            type: 'success'
                        })
                        that.closeFun(true)
                    } else {
                        that.$message({
                            message: res.info,
                            type: 'warning'
                        })
                    }
                })
            } else {
                return false
            }
        })
    },
  },
  watch:{
      //校验消防人员数不可以为00000
      personCountVal(val,oldVal){
          if(val!==oldVal){
              this.fireStationForm.personCount = Number(val)
          }
      },
      //校验消防车数不可以为00000
      carCountVal(val,oldVal){
          if(val!==oldVal){
              this.fireStationForm.carCount=Number(val)
           }
      }
  },
  computed:{
      personCountVal(){
          return this.fireStationForm.personCount;
      },
      carCountVal(){
          return this.fireStationForm.carCount;
      }
  }
}
</script>
<style lang="scss">
.fire-station-info-wrap {
    #unitName_mapInput {
        position: absolute;
        left: 5%;
        top: 8px;
        padding: 0 10px;
        width: 50%;
        background-color: rgba(255, 255, 255, 0.8);
        height: 38px;
        color: #333;
        border: 0;
        border-top: 1px solid #eee;
        border-left: 1px solid #eee;
        border-right: 1px solid #eee;
        border-radius: 2px 0 0 2px;
        box-shadow: 1px 1.5px 1px rgba(0,0,0,.25);
    }
}
.tangram-suggestion-main {
    z-index: 9999999999;
}
</style>

